// pages/student/do-test/index.js
import { Serve } from '../../../utils/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    test: {},
    titles: [],
    answer: [],
    file: '',
    path: {},
    alias: ''
  },

  // mark: 主观题作答函数(输入框)
  handleAnswerChange(e) {
    const { index } = e.currentTarget.dataset
    const value = e.detail.value
    const { answer } = this.data
    answer[index] = value
    this.setData({ answer })
  },

  // mark: 选择题作答函数
  handleSelectOptionChange(e) {
    const { index, titleindex } = e.currentTarget.dataset
    const { answer } = this.data
    answer[titleindex] = index
    this.setData({ answer })
  },

  // mark: 别名输入框
  handleAliasChange(e) {
    this.setData({ alias: e.detail.value })
  },

  // mark: "上传实验报告"按钮
  async chooseFile(e) {
    const isEqualString = (str1, str2) => {
      return str1.toLowerCase() === str2.toLowerCase()
    }
    const result = await wx.chooseMessageFile({
      count: 1,
      type: 'file',
      extensions: ['doc', 'docx']
    })
    
    const file = result.tempFiles[0]
    const arr = file.path.split('.')
    // 取后缀
    const suffix = arr[arr.length - 1]
    
    if (!isEqualString(suffix, 'doc') && !isEqualString(suffix, 'docx')) {
      wx.showToast({ title: '请上传word文档', icon: 'error', mask: true })
      return 0
    }

    this.setData({ path: result.tempFiles[0] })
  },

  // mark: "提交作答"按钮
  async confirmDone() {
    const { path, answer, test, alias } = this.data
    const openid = wx.getStorageSync('openid')
    let suffix = ''
    let filename = ''
    let flag = true
    if (test.has_file && JSON.stringify(path).length === 2) {
      wx.showToast({ title: '请上传实验报告', mask: true, duration: 800, icon: 'none' })
      return 0
    }
    if (test.has_file) {
      let arr = path.name.split('.')
      filename = path.name
      suffix = arr[arr.length - 1]
    }
    wx.showLoading({ title: '请耐心等待', mask: true })
    if (test.has_file) {
      // 上传文件
      const uploadResult = await wx.cloud.uploadFile({
        cloudPath: `${openid}/files/${path.name}`,
        filePath: path.path
      })
      const { fileID } = uploadResult

      await Serve.AddFile({
        test_id: test._id,        // 文件所属测试ID
        path: fileID,             // 文件云路径
        alias,                    // 文件别名
        class_id: test.class_id,  // 文件所属班级ID
        suffix,                   // 文件后缀
        filename                  // 文件名称
      })
    }

    await Serve.AddTestRecord({
      answer,
      test_id: test._id
    })

    wx.showToast({ title: '测试作答完成', mask: true, icon: 'success' })
    wx.switchTab({ url: '/pages/home/index' })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    const { test_id } = options
    wx.showLoading({ title: '获取测试内容', mask: true })
    const result = await Serve.GetTest(test_id)
    const title = result.test.name
    const answerLength = result.title.length
    const answer = Array(answerLength).fill('')
    wx.setNavigationBarTitle({ title })
    this.setData({ test: result.test, titles: result.title, answer })
    wx.hideLoading()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})